package com.qianbao.configuration;

import com.qianbao.domain.user.UserEntity;
import com.qianbao.service.user.SVUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jws.soap.SOAPBinding;


public class ShiroCustomRealm extends AuthorizingRealm {


    @Autowired
    private SVUserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        UserEntity entity = (UserEntity) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        return info;

    }


    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        String userName = authenticationToken.getPrincipal().toString();
        UserEntity entity = userService.findRegisterUserByPhone(userName);

        if (entity == null){
            //这里返回后会报出对应异常
            return null;
        }else {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,
                    entity.getPassword(),
                    this.getName());
            return info;
        }

    }



}
